package com.lzxuni.modules.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzxuni.modules.common.entity.Tree;
import com.lzxuni.modules.organization.entity.Dept;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.mapper.DeptMapper;
import com.lzxuni.modules.organization.service.DeptService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 单位部门表 服务实现类
 * </p>
 *
 * @author 孙志强
 * @since 2018-12-07
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
	@Override
	public List<Tree> getTree(String companyId) {
		List<Tree> list = baseMapper.queryListByParentId("0", companyId);
		getTreeDg(companyId,list);
		return list;
	}

	@Override
	public Boolean insert(User user, Dept dept) {
		if (user != null) {
			dept.setCreateUserId(user.getUserId());
			dept.setCreateUsername(user.getUsername());
		}
		int sortCode = 0;
		List<Dept> list = this.list(new QueryWrapper<Dept>().eq("parent_id", dept.getParentId()).eq("company_id", dept.getCompanyId()).orderByDesc("sort_code"));
		if (list != null & list.size() > 0) {
			sortCode = list.get(0).getSortCode()+1;
		}
		if(dept.getParentId().equals("-1")){
			dept.setParentId("0");
		}
		dept.setSortCode(sortCode);

		return this.save(dept);
	}

	@Override
	public Boolean update(User user, Dept dept) {
		Dept oldDept = this.getById(dept.getDeptId());
		if (user != null) {
			dept.setModifyUserId(user.getUserId());
			dept.setModifyUsername(user.getUsername());
		}
		if(dept.getParentId().equals("-1")){
			dept.setParentId("0");
		}
		dept.setSortCode(oldDept.getSortCode());
		return this.updateById(dept);
	}

	@Override
	public Object getMap(String ver) {
		List<Dept> list = this.list();
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();

		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> map2 = new HashMap<>();
			map2.put("parentId", list.get(i).getParentId());
			map2.put("name", list.get(i).getFullName());
			map2.put("companyId", list.get(i).getCompanyId());

			map1.put(list.get(i).getDeptId(), map2);
		}
		map.put("data", map1);
		map.put("ver", "123");
		return map;
	}


	/*私有方法区域*/
	private void getTreeDg(String companyId,List<Tree> ztreeList) {
		for (int i = 0; i < ztreeList.size(); i++) {
			Tree tree = ztreeList.get(i);
			List<Tree> treeList = baseMapper.queryListByParentId(companyId,tree.getId());
			tree.setChildNodes(treeList);
			getTreeDg(companyId,treeList);
		}
	}
}
